package com.financing.wap.util;


import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Map.Entry;
import java.util.Set;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class MessageUtil {
	
	/**
	 * 标题
	 */
	public static String KEY_TITLE = "title";
	
	/**
	 * 内容
	 */
	public static String KEY_CONTENT = "content";
	
	private static Map<String,Map<String,Object>> messageTemplate = new HashMap<String,Map<String,Object>>();
	
	static{
		Logger logger = Logger.getLogger(MessageUtil.class);
		
		SAXReader  saxReader = new SAXReader();
		try {
			Document document = saxReader.read(MessageUtil.class.getResourceAsStream("/messageTemplate.xml"));
			Element employees=document.getRootElement();   
			for(@SuppressWarnings("unchecked") Iterator<Element> typeElementIterator = employees.elementIterator();typeElementIterator.hasNext();){
				Element idElement = typeElementIterator.next();
					
				String type = idElement.attributeValue("type");
				Map<String,Object> 	idMessagesMap = new HashMap<String,Object>();
				
				for(@SuppressWarnings("unchecked") Iterator<Element> idElementIterator = idElement.elementIterator();idElementIterator.hasNext();){
					Element valueElement = idElementIterator.next();
					
					String id = valueElement.attributeValue("code");
					Map<String,Object> messageMap = new HashMap<String,Object>();
					
					for(@SuppressWarnings("unchecked") Iterator<Element> valueElementIterator = valueElement.elementIterator();valueElementIterator.hasNext();){
						Element valuesElement = valueElementIterator.next();
						
						messageMap.put(valuesElement.getName(), valuesElement.getData());
					}
					idMessagesMap.put(id, messageMap);
				}
				messageTemplate.put(type, idMessagesMap);
			}
		} catch (DocumentException e) {
			logger.error("Init MessageTemplate error :", e);
			throw new RuntimeException(e);
		}
		
	}
	
	
	/**
	 * 
	* @Title: getMessage 
	* @Description: 获取信息内容
	* @param   type  信息类型
	* @param   id   类型下面的ID
	* @param   params  需要在模板中替换的动态内容
	* @return Map<String,Object>  map里面的key键为title和content 
	* @throws
	 */
	@SuppressWarnings("unchecked")
	public static Map<String,Object> getMessage(String type,String id,Map<String,Object> params){
		
		Map<String,Object> typeMap = messageTemplate.get(type);
		
		if(typeMap == null){
			return null;
		}
		
		typeMap = (Map<String, Object>) typeMap.get(id);
		
		String messageTemplteContent = (String) typeMap.get("content");
		
		Set<Entry<String,Object>> set = params.entrySet();
		
		for(Entry<String,Object> entry : set){
			String tmp = "\\{"+entry.getKey()+"\\}";
			String v = "";
			if(null!=entry.getValue()){
				v = (String)entry.getValue();
			}
			messageTemplteContent = messageTemplteContent.replaceAll(tmp,v);
		}
		Map<String,Object> result = new HashMap<String,Object>();
		result.put(KEY_TITLE, typeMap.get(KEY_TITLE));
		result.put(KEY_CONTENT, messageTemplteContent);
		return result;
	}
	
	public static void main(String[] args) {
		
	}
	public static void sendEmail(InternetAddress[] sendTo, InternetAddress[] sendCopyTo, String eMailTitle, String eMailContent) throws AddressException, MessagingException{
		Properties props = new Properties();  
	     // 设置发送邮件的邮件服务器的属性（smtp服务器）  
	     props.put("mail.smtp.host", "smtp.exmail.qq.com");  
	     // 需要经过授权，也就是有户名和密码的校验，这样才能通过验证（一定要有这一条）  
	     props.put("mail.smtp.auth", "true");  
	     // 用刚刚设置好的props对象构建一个session  
	     Session session = Session.getDefaultInstance(props);  
	     // 有了这句便可以在发送邮件的过程中在console处显示过程信息，供调试使  
	     // 用（你可以在控制台（console)上看到发送邮件的过程）  
	     session.setDebug(true);  
	     // 用session为参数定义消息对象  
	     MimeMessage message = new MimeMessage(session);  
	      // 加载发件人地址  
	      message.setFrom(new InternetAddress("cuimo@superfa.cn"));  
	      // 加载收件人地址  
	      message.setRecipients(javax.mail.internet.MimeMessage.RecipientType.TO, sendTo); 
	      message.setRecipients(Message.RecipientType.CC,sendCopyTo);
	      // 加载标题  
	      message.setSubject(eMailTitle);  
	      // 向multipart对象中添加邮件的各个部分内容，包括文本内容和附件  
	      Multipart multipart = new MimeMultipart();  
	      // 设置邮件的文本内容  
	      BodyPart contentPart = new MimeBodyPart();
	      contentPart.setContent(eMailContent, "text/html; charset=utf-8");
	      multipart.addBodyPart(contentPart);  
	        
	      // 将multipart对象放到message中  
	      message.setContent(multipart);  
	      // 保存邮件  
	      message.saveChanges();  
	      // 发送邮件  
	      Transport transport = session.getTransport("smtp");  
	      // 连接服务器的邮箱 
	      String password= PropertiesUtils.getValue("server.superfa.cn.password");
	      transport.connect("smtp.exmail.qq.com", "cuimo@superfa.cn", password);  
	      // 把邮件发送出去  
	      transport.sendMessage(message, message.getAllRecipients());  
	      transport.close();  
	}
}
